package com.youlai.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youlai.system.common.result.Result;
import com.youlai.system.model.entity.HisCareHistory;
import com.youlai.system.model.entity.HisPatient;
import com.youlai.system.model.entity.SysDept;
import com.youlai.system.model.entity.SysRegisteredItem;
import com.youlai.system.model.form.CheckItemForm;
import com.youlai.system.service.HisCareHistoryService;
import com.youlai.system.service.HisPatientService;
import com.youlai.system.service.SysDeptService;
import com.youlai.system.service.SysRegisteredItemService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.sql.Wrapper;

/**
 * @author yao
 * @create 2024/9/3 下午5:52
 */
@Tag(name = "患者接口")
@RestController
@RequestMapping("/api/v1/hisParent")
@RequiredArgsConstructor
public class HisParentController {

    private final HisPatientService hisPatientService;
    private final SysDeptService deptService;
    private final HisCareHistoryService hisCareHistoryService;

    @Operation(summary = "根据身份证查询患者信息")
    @GetMapping("/getByIdCard")
    public Result<HisPatient> getRegisteredForm(String idCard) {
        try {
            QueryWrapper<HisPatient> wrapper = new QueryWrapper<>();
            wrapper.eq("id_card", idCard);
            HisPatient hisPatient = hisPatientService.getOne(wrapper);

            if (hisPatient != null) {
                return Result.success(hisPatient);
            } else {
                return Result.failed("未找到对应的患者信息");
            }
        } catch (Exception e) {
            return Result.failed("查询患者信息时发生错误: " + e.getMessage());
        }
    }

    @Operation(summary = "挂号")
    @PutMapping("/{deptId}")
    public Result register(@PathVariable Long deptId, @RequestBody @Valid HisPatient form) {
        QueryWrapper<HisPatient> wrapper = new QueryWrapper<>();
        wrapper.eq("id_card", form.getIdCard());
       if(hisPatientService.getOne(wrapper) ==null){
           form.setPatientId("HZ" + System.currentTimeMillis());
           hisPatientService.save(form);
       }
       HisCareHistory hisCareHistory = new HisCareHistory();
       hisCareHistory.setChId("CH" + System.currentTimeMillis());
       hisCareHistory.setPatientId(form.getPatientId());
       hisCareHistory.setPatientName(form.getName());
       hisCareHistory.setDeptId(deptId);
       hisCareHistory.setDeptName(deptService.getById(deptId).getName());
       hisCareHistory.setReceiveType("0");
       hisCareHistory.setIsContagious("0");
       hisCareHistory.setRegId("GH" + System.currentTimeMillis());
        return Result.success(hisCareHistoryService.save(hisCareHistory));
    }

}
